package com.liushao.util;

import com.liushao.exception.BusinessException;
import com.liushao.result.ResponseEnum;
import io.jsonwebtoken.*;
import org.springframework.util.StringUtils;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.util.Date;
/**
 * @author 陈修华
 * @ClassName JwtUtils
 * @description: TODO
 * @datetime 2025年 08月 07日 10:15
 * @version: 1.0
 */
public class JwtUtils {
    // token 过期时间 24小时
    private static long tokenExpiration = 24*60*60*1000;
    // token 签名密钥
    private static String tokenSignKey = "liushao3698";

    private static Key getKeyInstance(){
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        byte[] bytes = DatatypeConverter.parseBase64Binary(tokenSignKey);
        return new SecretKeySpec(bytes,signatureAlgorithm.getJcaName());
    }

    //  http://localhost/api/sms/send/18698789339

    public static String createToken(Long userId, String userName) {
        String token = Jwts.builder()
                .setSubject("liushao-user") // 主题
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration)) // 过期时间
                .claim("userId", userId) // 用户id
                .claim("userName", userName) // 用户名
                .signWith(SignatureAlgorithm.HS256, getKeyInstance()) // 签名算法
                .compressWith(CompressionCodecs.GZIP) // 压缩
                .compact(); // 压缩
        return token;
    }

    /**
     * 判断token是否有效
     * @param token
     * @return
     */
    public static boolean checkToken(String token) {
        if(StringUtils.isEmpty(token)) {
            return false;
        }
        try {
            Jwts.parser().setSigningKey(getKeyInstance()).parseClaimsJws(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }


    public static Long getUserId(String token) {
        Claims claims = getClaims(token);
        Integer userId = (Integer)claims.get("userId");
        return userId.longValue();
    }

    public static String getUserName(String token) {
        Claims claims = getClaims(token);
        return (String)claims.get("userName");
    }

    public static void removeToken(String token) {
        //jwttoken无需删除，客户端扔掉即可。
    }

    /**
     * 校验token并返回Claims
     * @param token
     * @return
     */
    private static Claims getClaims(String token) {
       if(StringUtils.isEmpty(token)) {
            // LOGIN_AUTH_ERROR(-211, "未登录"),
            try {
                throw new BusinessException(ResponseEnum.LOGIN_AUTH_ERROR);
            } catch (BusinessException e) {
                e.printStackTrace();
            }
        }
        try {
            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(getKeyInstance()).parseClaimsJws(token);
            Claims claims = claimsJws.getBody();
            return claims;
        } catch (Exception e) {
            try {
                throw new BusinessException(ResponseEnum.LOGIN_AUTH_ERROR);
            } catch (BusinessException e1) {
                e1.printStackTrace();
            }
        }

        return null;

        //return  null;
    }

    public static void main(String[] args) {
        String token = createToken(123456L, "liushao");

        //System.out.println(token);

        //  eyJhbGciOiJIUzI1NiIsInppcCI6IkdaSVAifQ.H4sIAAAAAAAAAKtWKi5NUrJSysksLc5IzNctLU4tUtJRSq0oULIyNDcwMjA0szA31lECiXumAMWMjE1MzSB8v8TcVIRWpVoAHhi800wAAAA.Z-Nvdj-8HErDZ9YjljzHNJZqOyCwnDbk60tEKscEt54

      //String  username=  getUserName("eyJhbGciOiJIUzI1NiIsInppcCI6IkdaSVAifQ.H4sIAAAAAAAAAKtWKi5NUrJSysksLc5IzNctLU4tUtJRSq0oULIyNDcwMjA0szA31lECiXumAMWMjE1MzSB8v8TcVIRWpVoAHhi800wAAAA.Z-Nvdj-8HErDZ9YjljzHNJZqOyCwnDbk60tEKscEt54");
        System.out.println(token);
        boolean b = checkToken(token);
        System.out.println(b);
        System.out.println(getUserId(token));

    }
}
